package sg.olaparty.network.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.salton123.coroutine.Ret
import com.salton123.log.XLog
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import sg.olaparty.network.RequestCenter.profileService
import sg.olaparty.network.request
import sg.olaparty.network.success
import sg.partying.lcb.api.resp.Resp
import java.io.File

/**
 * Time:2023/9/26 16:49
 * Author:
 * Description:
 */
class NetworkViewModel : ViewModel() {
    companion object {
        private const val TAG = "NetworkViewModel"
    }

    private val uploadRet by lazy { MutableLiveData<Ret<Resp<String>>>() }

    fun upload(localFilePath: String): MutableLiveData<Ret<Resp<String>>> {
        request({
            val file = File(localFilePath)
            val body = RequestBody.create("multipart/form-data".toMediaType(), file)
            val multipartBody = MultipartBody.Builder()
                .addFormDataPart("file", file.name, body)
                .setType(MultipartBody.FORM)
                .build()
            profileService.uploadAvatar(multipartBody)
        }, { apiResponse ->
            uploadRet.success(apiResponse)
        }, { errorCode: Int, errorMessage: String, throwable: Throwable? ->
            XLog.e(TAG, "[onFailed] error:$errorCode,$errorMessage,$throwable")
        })
        return uploadRet
    }
}